﻿using Microsoft.EntityFrameworkCore;
using NLog.Web;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Read.Api.Common;
using Sheep_Breeding.Read.Api.OperationServices.IServices;
using Sheep_Breeding.Read.Api.OperationServices.Services;
using System.Reflection;

namespace Sheep_Breeding.Read.Api.Extensions
{
    /// <summary>
    /// 拓展类方法  静态类  静态方法  this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x =>
            {
                // 正确的XML文档路径
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                
                // 检查文件是否存在
                if (File.Exists(xmlPath))
                {
                    x.IncludeXmlComments(xmlPath, true);
                }
                
                // 避免Swagger生成时出现架构ID冲突
                x.CustomSchemaIds(type => type.FullName);
                
                // 配置Swagger文档信息
                x.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title = "羊管理API",
                    Version = "v1",
                    Description = "羊管理系统API接口文档"
                });
            });

            //配置EFcore数据库
            builder.Services.AddDbContext<EFDbContext>(x =>
            {
                x.UseMySql(builder.Configuration["ConnectionStrings:Conn"]
                , ServerVersion.AutoDetect(builder.Configuration["ConnectionStrings:Conn"]), action =>
                {
                    //配置EFCore的重试策略
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,//最大重试次数
                        maxRetryDelay: TimeSpan.FromSeconds(60),//每次重试间隔时间最大延迟
                        errorNumbersToAdd: null
                        );

                }).EnableSensitiveDataLogging();//启动敏感数据日志记录，使与调试 但在生产环境中应谨慎使用避免泄露敏感信息

                //配置日志记录
                x.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddFilter(
                    category: DbLoggerCategory.Database.Name,//类别
                    level: LogLevel.Information//控制台日志
                    ).AddConsole()));
            });


            // 添加认证服务
            builder.Services.AddAuthentication();

            // 添加授权服务
            builder.Services.AddAuthorization();

            //注入
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BasreRepository<>));
            //注入组织管理
            builder.Services.AddScoped<IOrganizationServices, OrganizationServices>();

            //AutoMapper
            builder.Services.AddAutoMapper(typeof(MapperingProfil));
            
            // 处理可能的循环引用问题
            builder.Services.AddControllersWithViews()
                .AddJsonOptions(options => 
                {
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
                });
                
            //NLog注入
            builder.Host.UseNLog();
            return builder;
        }
    }
}
